/*
 * The MIT License
 *
 * Copyright 2015 Gavin Crayk.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.googlecode.census.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.googlecode.census.client.decoders.DefaultStringResponseDecoder;
import com.googlecode.census.client.decoders.HeartbeatResponseDecoder;
import java.io.IOException;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Gavin Crayk
 */
@ClientEndpoint(decoders = {
    HeartbeatResponseDecoder.class,
    DefaultStringResponseDecoder.class
})
public class CensusClientEndpointImpl implements CensusClientEndpoint {

    public static final Logger LOG = LoggerFactory.getLogger(CensusClientEndpointImpl.class);
    private final Gson gson;
    private Session session;
    private MessageHandler messageHandler;

    public CensusClientEndpointImpl() {
        gson = new GsonBuilder().create();
    }

    @OnOpen
    @Override
    public void onOpen(final Session session) {
        this.session = session;
    }

    @OnClose
    @Override
    public void onClose(final Session session, final CloseReason closeReason) {
        LOG.info("recieved closed: {} - {}", closeReason.getCloseCode(), closeReason.getReasonPhrase());
    }
    
    @OnError
    @Override
    public void onError(final Session session, final Throwable throwable) {
        LOG.error(throwable.getMessage());
    }

    @OnMessage
    @Override
    public void onMessage(final Object message) {
        LOG.debug("recieved {}", message.getClass().getName());
        if(null != messageHandler && message instanceof String) {
            messageHandler.handleMessage((String)message);
        }
    }

    @Override
    public boolean isOpen() {
        return (null != session && session.isOpen());
    }

    @Override
    public void sendMessage(final ServiceMessage message) {
        final String messageToSend = gson.toJson(message);
        LOG.debug("Sending message: {}", messageToSend);
        this.session.getAsyncRemote().sendText(messageToSend);
    }

    @Override
    public void addMessageHandler(final MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    @Override
    public void close() {
        if (null != session && session.isOpen()) {
            try {
                session.close();
            } catch (IOException ex) {
                LOG.error("Unable to close session: {}", ex.getMessage());
            }
        }
    }

}
